package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.User;
import xyz.zchao.blog.service.UserService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import java.util.List;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/5/17 1:59
 */
@RestController
@RequestMapping("/user")
public class UserManageController {
    @Autowired
    private UserService userService;

    @IgnoreToken
    @GetMapping("/list")
    public PageResultVO getUsers(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit) {
        List<User> users = userService.retrieveAllByPaging(page, limit);
        //不输出密码
        users.stream().forEach(user -> {
            user.setUserPassword(null);
        });
        long count = userService.getCount();
        return new PageResultVO(ResultCode.SUCCESS, users, count);
    }

    @IgnoreToken
    @GetMapping("/list/{uid}")
    public ResultVO getUser(@PathVariable("uid") Integer uid) {
        User user = userService.retrieveById(uid);
        user.setUserPassword(null);
        return new ResultVO(ResultCode.SUCCESS, user);
    }

    @PutMapping("/list/{uid}")
    public ResultVO updateUser(@PathVariable("uid") Integer uid, @RequestBody User record) {
        record.setUserId(uid);
        userService.update(record);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @DeleteMapping("/list/{uid}")
    public ResultVO deleteUser(@PathVariable("uid") Integer uid) {
        userService.deleteById(uid);
        return new ResultVO(ResultCode.SUCCESS, null);
    }

    @IgnoreToken
    @GetMapping("/search")
    public ResultVO searchUsers(@RequestParam String keyword) {
        List<User> users = userService.fuzzyFindUserByUserName(keyword);
        users.stream().forEach(user -> {
            user.setUserPassword(null);
        });
        return new ResultVO(ResultCode.SUCCESS, users);
    }
}
